/*
 * JSF Toolkit Component Framework
 * Copyright (C) 2007 Noah Sloan <iamnoah A-T gmail D0T com>
 * 
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 */
package com.jsftoolkit.utils;

import java.io.IOException;
import java.util.Stack;

import javax.faces.component.UIComponent;
import javax.faces.context.ResponseWriter;
import javax.faces.context.ResponseWriterWrapper;

/**
 * Records all the tags open by the wrapped {@link ResponseWriter}.
 * {@link #closeAllOpen()} will close any tags that have not been closed.
 * 
 * @author noah
 * 
 */
public class RecordTagsWriter extends ResponseWriterWrapper {

	private final transient ResponseWriter wrapped;

	private transient Stack<String> open = new Stack<String>();

	public RecordTagsWriter(ResponseWriter wrapped) {
		super();
		this.wrapped = wrapped;
	}

	public ResponseWriter getWrapped() {
		return wrapped;
	}

	@Override
	public void startElement(String name, UIComponent component)
			throws IOException {
		super.startElement(name, component);
		open.push(name);
	}

	@Override
	public void endElement(String name) throws IOException {
		super.endElement(name);
		open.pop();
	}

	/**
	 * Closes any tags that have not been closed that were opened by this
	 * writer.
	 * 
	 * @throws IOException
	 */
	public void closeAllOpen() throws IOException {
		while (!open.isEmpty()) {
			wrapped.endElement(open.pop());
		}
	}
}
